#include "app_common.h"
#include "sys/time.h"
#include <stdio.h>
#include <stdlib.h>
#include "unistd.h"
#include "log.h"
#include "string.h"

long app_common_get_curtime_ts(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (long)(tv.tv_sec * 1000 + tv.tv_usec / 1000);
}

void app_common_print_hex(const char *buf, int len)
{
    int i;
    for (i = 0; i < len; i++)
    {
        printf("%02x ", buf[i]);
    }
    printf("\n");
}

char *app_common_bytes_to_hexstr(const char *data, int len)
{
    char *hexstr = (char *)malloc(len * 2 + 1);
    if (hexstr == NULL)
    {
        return NULL;
    }
    for (int i = 0; i < len; i++)
    {
        sprintf(hexstr + i * 2, "%02x", (unsigned char)data[i]);
    }
    hexstr[len * 2] = '\0'; // 添加字符串结束符
    // 释放内存
    return hexstr;
}

int app_common_hexstr_to_bytes(const char *hexstr, char *byte_buf, int buf_len)
{
    int len = strlen(hexstr);
    if (len % 2 != 0 || len / 2 > buf_len)
    {
        log_error("hexstr length is not even or too long");
        return -1; // 错误：长度不合法
    }

    for (int i = 0; i < len; i += 2)
    {
        sscanf(hexstr + i, "%2hhx", &byte_buf[i / 2]);
    }
    return len / 2; // 返回转换后的长度
}
